package com.zxt.dlna.activity.device;

import android.content.Context;
import android.support.annotation.NonNull;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.TextView;

import com.zxt.dlna.R;
import com.zxt.dlna.application.BaseApplication;
import com.zxt.dlna.dmp.DeviceItem;

import java.util.List;

public class DevAdapter extends ArrayAdapter<DeviceItem> {

    private static final String TAG = "DeviceAdapter";

    private final LayoutInflater mInflater;

    private final List<DeviceItem> deviceItems;

    public DevAdapter(Context context, int textViewResourceId, List<DeviceItem> objects) {
        super(context, textViewResourceId, objects);
        this.mInflater = ((LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE));
        this.deviceItems = objects;
    }

    @Override
    public int getCount() {
        return this.deviceItems.size();
    }

    @Override
    public DeviceItem getItem(int paramInt) {
        return this.deviceItems.get(paramInt);
    }

    @Override
    public long getItemId(int paramInt) {
        return paramInt;
    }

    @Override
    @NonNull
    public View getView(int position, View view, @NonNull ViewGroup viewGroup) {

        DevHolder holder;
        if (view == null) {
            view = this.mInflater.inflate(R.layout.dmr_item, null);
            holder = new DevHolder();
            holder.filename = ((TextView) view
                    .findViewById(R.id.dmr_name_tv));
            holder.checkBox = ((CheckBox) view.findViewById(R.id.dmr_cb));
            view.setTag(holder);
        } else {
            holder = (DevHolder) view.getTag();
        }

        DeviceItem item = this.deviceItems.get(position);
        holder.filename.setText(item.toString());
        if (null != BaseApplication.deviceItem
                && BaseApplication.deviceItem.equals(item)) {
            holder.checkBox.setChecked(true);
        } else {
            holder.checkBox.setChecked(null != BaseApplication.dmrDeviceItem
                    && BaseApplication.dmrDeviceItem.equals(item));
        }
        return view;
    }

    public static final class DevHolder {
        public TextView filename;
        public CheckBox checkBox;
    }

}